package a66weding.com.jiehuntong.fragment.order;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;

import org.xutils.x;

import java.math.BigDecimal;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.me.MeIndentActivity;
import a66weding.com.jiehuntong.activity.me.MePayActivity;
import a66weding.com.jiehuntong.activity.me.MeShoppingCartActivity;
import a66weding.com.jiehuntong.activity.order.EvaluationActivity;
import a66weding.com.jiehuntong.activity.order.OrderDetailsActivity;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MeShoppingCartBean;
import a66weding.com.jiehuntong.beans.MyOrderBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.StrUtil;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;

/**
 * @version :
 * @creator : AxDu
 * @create-time : 2016/8/30
 * @description :
 */
public class AllOrderFragment extends BaseOrderFragment implements View.OnClickListener, OnNetResultListener {
    private MeIndentActivity mIndentActivity;
    private ExpandableListView mExListview;
    private List<MyOrderBean.DataBean> orderList;
    private MyExpandListAdapter mAdapter;
    private XRefreshView mRefreshView;
    private boolean isDownRefresh;
    private boolean isPullLoadMore;
    private int pagerIndex;
    private int whereType=0;
    private int memberID;
    private int currentCategoryId;
    @Override
    public void getData() {
        super.getData();
    }

    @Override
    public View initView(LayoutInflater inflater, Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_order_allorder, null);
        mExListview = (ExpandableListView) contentView.findViewById(R.id.lview_orderList);
        mRefreshView = (XRefreshView) contentView.findViewById(R.id.xrefreshview_allorder);
        initRefreshView();
        return contentView;
    }
    @Override
    public void initData() {
        mIndentActivity = (MeIndentActivity) getActivity();
        orderList = mIndentActivity.getOrderList();
        memberID = mIndentActivity.getMemberID();
        currentCategoryId = mIndentActivity.getCurrentCategoryId();
        getOrderData(currentCategoryId,1,whereType);
    }

    private void getOrderData(int category,int pagerIndex,int whereType){
        String orderUrl= RequestCode.get_MyOrderDetail;
        orderUrl += "&memberID="+memberID+"&category="+category+"&pageIndex="+pagerIndex+"&whereType="+whereType;
        HttpRequestBean httpRequestBeans = new HttpRequestBean(RequestCode.GETREQUEST,
                orderUrl, this, MyOrderBean.class, RequestCode.get_MyOrderDetail);
        HttpHandleUtil.executeCommonGet(mIndentActivity, httpRequestBeans);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
                case R.id.lay_order_child:
                    int groupPosition = (int) v.getTag();
                    MyOrderBean.DataBean orderDataBean = orderList.get(groupPosition);
                    //转到订单详情

                    Intent intent = new Intent(mIndentActivity, OrderDetailsActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("orderDataBean",orderDataBean);
                    intent.putExtras(bundle);
                    mIndentActivity.startActivity(intent);


                    break;

        }
    }



    private void setMoney(List<MyOrderBean.DataBean> orderList) {
        for (int i = 0; i < orderList.size(); i++) {
            float groupMoney = 0;
            int buycount=0;
            List<MyOrderBean.DataBean.MyOrderDetailBean> myOrderDetail = orderList.get(i).getMyOrderDetail();
            for (int j = 0; j < myOrderDetail.size(); j++) {
                int buyNumber = myOrderDetail.get(j).getBuyNumber();
                float singlePrice = (float) (myOrderDetail.get(j).getSinglePrice());
                float totalprice = buyNumber * singlePrice;

                buycount += buyNumber;

                groupMoney += totalprice;

            }

            orderList.get(i).setGroupMoney(StrUtil.floatNumDeal( groupMoney));
            orderList.get(i).setGroupconunt(buycount);
        }

    }



    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if(data instanceof MyOrderBean) {
            MyOrderBean orderdata= (MyOrderBean) data;
            if (isDownRefresh){
                mRefreshView.stopRefresh();
                isDownRefresh=false;
            }
            switch (orderdata.getResCode()) {
                    case "0000":
                        orderList = orderdata.getData();
                        if(orderList!=null) {
                            setMoney(orderList);
                            mAdapter = new MyExpandListAdapter();
                            mExListview.setAdapter(mAdapter);
                            mExListview.setGroupIndicator(null);
                            mExListview.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
                                @Override
                                public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                                    return true;
                                }
                            });
                            for (int i = 0; i < orderList.size(); i++) {
                                mExListview.expandGroup(i);
                            }
                        }


                    break;
                    case "0003":
                        orderList.clear();
                        if(mAdapter!=null) {
                            mAdapter.notifyDataSetChanged();
                        }

                        break;
            }

        }
    }

    @Override
    public void onError(ErrorBean errorBean) {

    }


    public class MyExpandListAdapter extends BaseExpandableListAdapter {

        @Override
        public int getGroupCount() {
            return orderList.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            List<MyOrderBean.DataBean.MyOrderDetailBean> myOrderDetail = orderList.get(groupPosition).getMyOrderDetail();

            return myOrderDetail.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return orderList.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            MyOrderBean.DataBean.MyOrderDetailBean myOrderDetailBean = null;
            MyOrderBean.DataBean dataBean = orderList.get(groupPosition);
            if (dataBean != null) {
                myOrderDetailBean = dataBean.getMyOrderDetail().get(childPosition);
            }
            return myOrderDetailBean;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {

            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            MyOrderBean.DataBean dataBean = orderList.get(groupPosition);
            GroupHolder mHolder;

            if(convertView==null) {
                mHolder = new GroupHolder();
                convertView = View.inflate(mIndentActivity, R.layout.item_me_indent_group, null);
                mHolder.mGroupTitleTv = (TextView) convertView.findViewById(R.id.tv_order_grouptitle);
                mHolder.mGroupstateTv =  (TextView) convertView.findViewById(R.id.tv_order_state);
                convertView.setTag(mHolder);
            }else{
                mHolder = (GroupHolder) convertView.getTag();
            }
            mHolder.mGroupTitleTv.setText(dataBean.getBusinessName());


            mHolder.mGroupstateTv.setText(dataBean.getOrderStateStr());

            if(6==dataBean.getOrderState()) {
                boolean isAllPinjia= isAllpinjia(dataBean);
                if(isAllPinjia) {
                    mHolder.mGroupstateTv.setText("已完成");
                }else{
                    mHolder.mGroupstateTv.setText("待评价");
                }
            }


            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            MyOrderBean.DataBean dataBean = orderList.get(groupPosition);
            List<MyOrderBean.DataBean.MyOrderDetailBean> myOrderDetail = dataBean.getMyOrderDetail();
            MyOrderBean.DataBean.MyOrderDetailBean myOrderDetailBean = myOrderDetail.get(childPosition);

//            cartItemsBean.
            ItemHolder mHolder;
            if(convertView==null) {
                mHolder = new ItemHolder();
                convertView = View.inflate(mIndentActivity, R.layout.item_me_indent_child, null);
                mHolder.mIndentIv = (ImageView) convertView.findViewById(R.id.img_indent);
                mHolder.mChildTitleTv = (TextView) convertView.findViewById(R.id.tv_order_childtitle);
                mHolder.mGroupCountTv =  (TextView) convertView.findViewById(R.id.tv_account);
                mHolder.mGroupPayTv =  (TextView) convertView.findViewById(R.id.tv_me_pay_money);
                mHolder.mGroupShipPayTv =  (TextView) convertView.findViewById(R.id.tv_shipmoney);
                mHolder.mToPayTv =  (TextView) convertView.findViewById(R.id.tv_order_topay);

                mHolder.mGroupInfoLay = (LinearLayout) convertView.findViewById(R.id.lay_order_groupInfo);

                mHolder.mChildLay = (LinearLayout) convertView.findViewById(R.id.lay_order_child);


                convertView.setTag(mHolder);
            }else{
                mHolder = (ItemHolder) convertView.getTag();
            }

            x.image().bind(mHolder.mIndentIv, myOrderDetailBean.getProductPicMain());
            mHolder.mChildTitleTv.setText(myOrderDetailBean.getProductName());



            if(isLastChild) {
                mHolder.mGroupInfoLay.setVisibility(View.VISIBLE);
                TextView payMoneyTv = (TextView) mHolder.mGroupInfoLay.findViewById(R.id.tv_me_pay_money);
                TextView shipMoneyTv =  (TextView) mHolder.mGroupInfoLay.findViewById(R.id.tv_shipmoney);
                RelativeLayout topayLay = (RelativeLayout) mHolder.mGroupInfoLay.findViewById(R.id.rlay_order_topay);
                TextView toPayTv = (TextView) mHolder.mGroupInfoLay.findViewById(R.id.tv_order_topay);


                mHolder.mGroupCountTv.setText("共"+dataBean.getGroupconunt()+"件商品");
                payMoneyTv.setText("￥"+dataBean.getGroupMoney());
                shipMoneyTv.setText("￥"+dataBean.getDm_PSMoney());


                if(dataBean.getOrderState()==1 || "待审核".equals(dataBean.getOrderStateStr())) {
                    topayLay.setVisibility(View.VISIBLE);

                    toPayTv.setTag(groupPosition);

                    toPayTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int groupPosition = (int) v.getTag();

                            //去付款
                            //mIndentActivity
                            Intent intent = new Intent(mIndentActivity, MePayActivity.class);
                            MyOrderBean.DataBean dataBean1 = orderList.get(groupPosition);


                            //跳到购物车：
//                            Intent intent = new Intent(mIndentActivity,.class);
//                            MyOrderBean.DataBean dataBean1 = orderList.get(groupPosition);
//                            int businessID = dataBean1.getBusinessID();
//                            List<MyOrderBean.DataBean.MyOrderDetailBean> myOrderDetailList = dataBean1.getMyOrderDetail();
//                            int[] goodsIDs = new int[myOrderDetailList.size()+1];
//                            for (int i = 0; i < myOrderDetailList.size(); i++) {
//                                int productID = myOrderDetailList.get(i).getProductID();
//                                goodsIDs[i]=productID;
//                            }
//                            goodsIDs[myOrderDetailList.size()]=businessID;
//                            intent.putExtra("isSelectGoods",true);
//                            intent.putExtra("waitpayId",goodsIDs);
//                            startActivity(intent);


                            //跳到支付界面
                            String ordersNumber = dataBean1.getOrdersNumber();
                            float groupMoney = dataBean1.getGroupMoney();
                            double payMoney = dataBean1.getDm_PSMoney() + groupMoney;
                            float newPayMoney=StrUtil.floatNumDeal((float) payMoney);
                            intent.putExtra("isFromMyOrder",true);
                            intent.putExtra("ordersNumber",ordersNumber);
                            intent.putExtra("newPayMoney",newPayMoney);
                            mIndentActivity.startActivity(intent);

                        }
                    });


                }else{
                    topayLay.setVisibility(View.GONE);
                }

            }else{
                mHolder.mGroupInfoLay.setVisibility(View.GONE);



            }
            mHolder.mChildLay.setTag(groupPosition);
            mHolder.mChildLay.setOnClickListener(AllOrderFragment.this);


            return convertView;
        }



        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
        // 父View的Holder
        class GroupHolder {
            TextView mGroupTitleTv;
            TextView mGroupstateTv;


        }

        // 子View的Holder
        class ItemHolder {

            ImageView mIndentIv;
            TextView mChildTitleTv;
            TextView mGroupCountTv;
            TextView mGroupPayTv;
            TextView mGroupShipPayTv;
            TextView mToPayTv;
            LinearLayout mGroupInfoLay;
            LinearLayout mChildLay;


        }
    }


    private boolean isAllpinjia(MyOrderBean.DataBean dataBean) {
        boolean flag=true;
        List<MyOrderBean.DataBean.MyOrderDetailBean> myOrderDetailList = dataBean.getMyOrderDetail();
        for (int i = 0; i < myOrderDetailList.size(); i++) {
            int i_orderComment = myOrderDetailList.get(i).getI_OrderComment();
            if(0==i_orderComment) {
                flag=false;
                return flag;
            }
        }

        return flag;
    }


    @Override
    public void notifydata(int categoryId) {
//        Log.e("Log", "AllOrderFragment notifydata: categoryId=" +categoryId);
        pagerIndex=1;
        getOrderData(categoryId,1,whereType);
    }

    //初始化上啦刷新
    private void initRefreshView() {
        //是否允许下拉刷新
        mRefreshView.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        mRefreshView.setPullLoadEnable(false);
        // 设置刷新完成以后，headerview固定的时间
        mRefreshView.setPinnedTime(1000);
        // 静默加载模式不能设置footerview
        // 设置支持自动刷新
        mRefreshView.setAutoLoadMore(false);

        mRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh() {
                isDownRefresh = true;
                isPullLoadMore=false;
                pagerIndex=1;
               getOrderData(currentCategoryId,1,whereType);

            }

            @Override
            public void onLoadMore(boolean isSlience) {
                isPullLoadMore = true;
                isDownRefresh = false;

            }
        });
    }






}
